'use strict';

app.controller('AppCtrl', ['$scope', '$window', '$rootScope',
    function($scope, $window, $rootScope) {
        $rootScope.getSgObj = function(key) {
            var obj = $window.sessionStorage.getItem(key);
            return JSON.parse(obj);
        }
        $rootScope.setSgObj = function(key, value) {
            return $window.sessionStorage.setItem(key, JSON.stringify(value));
        }
    }
]);

app.controller('FillCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
        $scope.mappers = {};

        var user = $rootScope.getSgObj('LOGINUSER');
        if (!user){
            window.location.href = "";
        }

        R.getAddressList().then(function(data){
            $scope.mappers.address = data.bizData;
            $scope.model.l1 = $scope.mappers.address[0];
        });

        $scope.model = {
            l1: null,
            l2: null,
            l3: null
        };

        $scope.item = {
            companyName: '',
            phone: ''
        }

        $scope.$watch('model.l1', function(){
            $scope.model.l2 = null;
        });

        $scope.$watch('model.l2', function(){
            $scope.model.l3 = null;
        });

        $scope.submit = function(){
            if ($scope.model.l1) {
                $scope.item.countryId = $scope.model.l1.id;
            }
            if ($scope.model.l2) {
                $scope.item.provinceId = $scope.model.l2.id;
            }
            if ($scope.model.l3) {
                $scope.item.cityId = $scope.model.l3.id;
            }

            $scope.item.id = $rootScope.getSgObj('LOGINUSER').id;

            R.perfectUserInfo($scope.item).then(function(data){
                if (data.rtnCode == '0000000'){
                    window.location.href = 'index.html';
                }else{
                    $scope.error = data.msg;
                }
            });
        } 
    }
]);